/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DialogMantenimiento.java
 *
 * Created on 14/02/2011, 01:05:21 PM
 */

package com.catosist.run.application.vehiculo.mantenimiento;

import com.catosist.run.business.gestorMantenimiento.GestorMantenimiento;
import com.catosist.run.services.MantenimientoDTO;
import java.util.Iterator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
import javax.swing.DefaultComboBoxModel;

import ca.odell.glazedlists.swing.AutoCompleteSupport;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.TextFilterator;
import ca.odell.glazedlists.matchers.TextMatcherEditor;
import com.catosist.run.services.ComprobanteDTO;
import java.awt.event.ContainerListener;

import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.Format;
import java.util.*;
import javax.swing.JComboBox;
/**
 *
 * @author igorov
 */
public class DialogMantenimiento extends javax.swing.JDialog {

    /** Creates new form DialogMantenimiento */
    public DialogMantenimiento(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public DialogMantenimiento(java.awt.Frame parent, boolean modal, int vehiculoId, int mantenimientoId) {
        super(parent, modal);
        initComponents();
        
        iniciar();
        refresh();
        this.vehiculoId = vehiculoId;
        this.mantenimientoId = mantenimientoId;


        llenarComboDescripcion();
        llenarComboDetalle();
        llenarComboUnidadMedida();

        if(mantenimientoId != 0){
            MantenimientoDTO mantenimientoDTO = gestorMantenimiento.getById(mantenimientoId);
            this.setTitle("Editar mantenimiento " + mantenimientoId);
//            spnCantidad2.setValue(mantenimientoDTO.getCantidad());
            txtCantidad.setText(String.valueOf(mantenimientoDTO.getCantidad()));
            dtcFecha.setDate(mantenimientoDTO.getFecha());
            txtPrecioUnitario.setText(String.valueOf(mantenimientoDTO.getPreciounitario()));
        }
        else
            this.setTitle("Nuevo mantenimiento");
    }

    private void llenarComboDescripcion(){
        this.posibles = gestorMantenimiento.getAllByDescription();
        Url[] URLS = new Url[posibles.size()];
        for (int i = 0; i < posibles.size(); i++) {
            MantenimientoDTO tmp = posibles.get(i);
            URLS[i] = new Url(tmp.getDescripcion());
        }

        final EventList<Url> urls = GlazedLists.eventList(Arrays.asList(URLS));
        AutoCompleteSupport support = AutoCompleteSupport.install(cmbDescripcion, urls, new URLTextFilterator(), new UrlFormat());
        support.setFilterMode(TextMatcherEditor.CONTAINS);

        if (mantenimientoId != 0) {
            MantenimientoDTO mantenimientoDTO = gestorMantenimiento.getById(mantenimientoId);
            int indice = 0;
            for (int i = 0; i < URLS.length; i++) {
                if (mantenimientoDTO.getDescripcion().equals(URLS[i].getLocation())) {
                    indice = i;
                }
            }
            cmbDescripcion.setSelectedIndex(indice);
        }
    }

    private void llenarComboDetalle(){
        this.posibles = gestorMantenimiento.getAllByDetalle();
        Url[] URLS = new Url[posibles.size()];
        for (int i = 0; i < posibles.size(); i++) {
            MantenimientoDTO tmp = posibles.get(i);
            URLS[i] = new Url(tmp.getDetalle());
        }

        final EventList<Url> urls = GlazedLists.eventList(Arrays.asList(URLS));
        AutoCompleteSupport support = AutoCompleteSupport.install(cmbDetalle, urls, new URLTextFilterator(), new UrlFormat());
        support.setFilterMode(TextMatcherEditor.CONTAINS);

        if (mantenimientoId != 0) {
            MantenimientoDTO mantenimientoDTO = gestorMantenimiento.getById(mantenimientoId);
            int indice = 0;
            for (int i = 0; i < URLS.length; i++) {
                if (mantenimientoDTO.getDetalle().equals(URLS[i].getLocation())) {
                    indice = i;
                }
            }
            cmbDetalle.setSelectedIndex(indice);
        }
    }

    private void llenarComboUnidadMedida(){
        this.posibles = gestorMantenimiento.getAllByUnidadMedida();
        Url[] URLS = new Url[posibles.size()];
        for (int i = 0; i < posibles.size(); i++) {
            MantenimientoDTO tmp = posibles.get(i);
            URLS[i] = new Url(tmp.getUnidadmedida());
        }

        final EventList<Url> urls = GlazedLists.eventList(Arrays.asList(URLS));
        AutoCompleteSupport support = AutoCompleteSupport.install(cmbUnidadMedida, urls, new URLTextFilterator(), new UrlFormat());
        support.setFilterMode(TextMatcherEditor.CONTAINS);

        if (mantenimientoId != 0) {
            MantenimientoDTO mantenimientoDTO = gestorMantenimiento.getById(mantenimientoId);
            int indice = 0;
            for (int i = 0; i < URLS.length; i++) {
                if (mantenimientoDTO.getUnidadmedida().equals(URLS[i].getLocation())) {
                    indice = i;
                }
            }
            cmbUnidadMedida.setSelectedIndex(indice);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cmbDescripcion = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        btnAgregar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        lblTitle = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        dtcFecha = new com.toedter.calendar.JDateChooser("yyyy/MM/dd", "####/##/##", '_');
        jLabel4 = new javax.swing.JLabel();
        txtPrecioUnitario = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        cmbDetalle = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        cmbUnidadMedida = new javax.swing.JComboBox();
        txtCantidad = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.catosist.run.application.desktopapplication.DesktopApplication.class).getContext().getResourceMap(DialogMantenimiento.class);
        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        cmbDescripcion.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        cmbDescripcion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbDescripcion.setName("cmbDescripcion"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        btnAgregar.setText(resourceMap.getString("btnAgregar.text")); // NOI18N
        btnAgregar.setName("btnAgregar"); // NOI18N
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnCancelar.setText(resourceMap.getString("btnCancelar.text")); // NOI18N
        btnCancelar.setName("btnCancelar"); // NOI18N
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        lblTitle.setText(resourceMap.getString("lblTitle.text")); // NOI18N
        lblTitle.setName("lblTitle"); // NOI18N

        jLabel3.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        dtcFecha.setDate(new java.util.Date());
        dtcFecha.setName("dtcFecha"); // NOI18N
        dtcFecha.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                dtcFechaFocusLost(evt);
            }
        });

        jLabel4.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        txtPrecioUnitario.setText(resourceMap.getString("txtPrecioUnitario.text")); // NOI18N
        txtPrecioUnitario.setName("txtPrecioUnitario"); // NOI18N

        jLabel5.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        cmbDetalle.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        cmbDetalle.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbDetalle.setName("cmbDetalle"); // NOI18N

        jLabel6.setFont(resourceMap.getFont("jLabel6.font")); // NOI18N
        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        cmbUnidadMedida.setFont(resourceMap.getFont("cmbUnidadMedida.font")); // NOI18N
        cmbUnidadMedida.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbUnidadMedida.setName("cmbUnidadMedida"); // NOI18N

        txtCantidad.setText(resourceMap.getString("txtCantidad.text")); // NOI18N
        txtCantidad.setName("txtCantidad"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbDetalle, 0, 592, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(cmbDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtPrecioUnitario, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(33, 33, 33)
                                .addComponent(lblTitle))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel4)
                                .addGap(30, 30, 30)
                                .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel6)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbUnidadMedida, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                        .addComponent(dtcFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(27, 27, 27))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(277, Short.MAX_VALUE)
                .addComponent(btnAgregar)
                .addGap(18, 18, 18)
                .addComponent(btnCancelar)
                .addGap(240, 240, 240))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblTitle)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4))
                    .addComponent(cmbUnidadMedida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel6)
                        .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel3)
                    .addComponent(dtcFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(txtPrecioUnitario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(cmbDetalle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAgregar)
                    .addComponent(btnCancelar))
                .addGap(21, 21, 21))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {cmbDescripcion, txtPrecioUnitario});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        // TODO add your handling code here:

        String unidadmedida = ((Url)this.cmbUnidadMedida.getSelectedItem()).getLocation();
        String descripcion = ((Url)this.cmbDescripcion.getSelectedItem()).getLocation();
        String detalle = ((Url)this.cmbDetalle.getSelectedItem()).getLocation();
//        int cantidad = spnCantidad2.getValue();

        Float cantidad = Float.parseFloat(txtCantidad.getText());
        Float preciounitario = Float.parseFloat(txtPrecioUnitario.getText());
        preciounitario = Float.valueOf((float) Math.round(preciounitario * 100)/100);
        Float total = cantidad * preciounitario;

        MantenimientoDTO mantenimientoDTO = new MantenimientoDTO();
//        System.out.println("Id de mantenimiento: " + mantenimientoId);
        mantenimientoDTO.setId(mantenimientoId);
        mantenimientoDTO.setCantidad(cantidad);
        mantenimientoDTO.setDetalle(detalle);
        mantenimientoDTO.setPreciounitario(preciounitario);
        mantenimientoDTO.setDescripcion(descripcion);
        mantenimientoDTO.setTotal(total);
        mantenimientoDTO.setUnidadmedida(unidadmedida);
        mantenimientoDTO.setFecha(this.dtcFecha.getDate());
        gestorMantenimiento.saveOrUpdate(mantenimientoDTO, vehiculoId);

        this.setVisible(false);
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void dtcFechaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dtcFechaFocusLost
        this.cmbDescripcion.requestFocus();
}//GEN-LAST:event_dtcFechaFocusLost

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                DialogMantenimiento dialog = new DialogMantenimiento(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    public void iniciar(){
        ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
        gestorMantenimiento = (GestorMantenimiento) ctx.getBean("gestorMantenimiento");
    }

    public void refresh() {
        List<MantenimientoDTO> mantenimientoDTOs = gestorMantenimiento.getAll();
//        System.out.println(mantenimientoDTOs.size());
        DefaultComboBoxModel model = new DefaultComboBoxModel();

        for (Iterator<MantenimientoDTO> it = mantenimientoDTOs.iterator(); it.hasNext();) {
            MantenimientoDTO mantenimientoDTO = it.next();
//            model.addElement(mantenimientoDTO.getDescripcion());
            model.addElement("Item");
        }
//        this.cmbDescripcionTipo.setModel(model);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JComboBox cmbDescripcion;
    private javax.swing.JComboBox cmbDetalle;
    private javax.swing.JComboBox cmbUnidadMedida;
    private com.toedter.calendar.JDateChooser dtcFecha;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JTextField txtCantidad;
    private javax.swing.JTextField txtPrecioUnitario;
    // End of variables declaration//GEN-END:variables
    private ApplicationContext ctx;
    private int vehiculoId;
    private int mantenimientoId;
    private GestorMantenimiento gestorMantenimiento;
    private List<MantenimientoDTO> posibles;
//    HashMap<Integer, Integer> mapPosiblesIds;

    public static final class Url {

        private final String location;

        public Url(String location) {
            this.location = location;
        }

        public String getLocation() {
            return location;
        }
    }

    private static final class URLTextFilterator implements TextFilterator<Url> {
        public void getFilterStrings(List<String> baseList, Url element) {
            final String location = element.getLocation();
            baseList.add(location);

            if (location.startsWith("http://"))
                baseList.add(location.substring(7));
            if (location.startsWith("http://www."))
                baseList.add(location.substring(11));
        }
    }

    private static final class UrlFormat extends Format {
        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
            if (obj != null)
                toAppendTo.append(((Url) obj).getLocation());
            return toAppendTo;
        }

        public Object parseObject(String source, ParsePosition pos) {
            return new Url(source);
        }
    }
}
